package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"house/models"
	"time"

	"house/house_rpc/house_rpc"
	"house/house_rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *house_rpc.ListRequest) (*house_rpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	var Houses []models.House
	var Data house_rpc.ListResponse
	var key = fmt.Sprintf("page=%d", page)
	json_get, _ := models.RDB.Get(models.Ctx, key).Result()
	if json_get == "" {
		if err := models.DB.Limit(5).Offset(int(page-1) * 5).Find(&Houses).Error; err != nil {
			return &house_rpc.ListResponse{}, err
		}
		json_set, _ := json.Marshal(&Houses)
		models.RDB.Set(models.Ctx, key, json_set, 5*time.Minute)
	} else {
		json.Unmarshal([]byte(json_get), &Houses)
	}
	for _, house := range Houses {
		var get house_rpc.House
		get.Id = int64(house.ID)
		get.Status = house.Status
		get.Address = house.Address
		get.HouseName = house.HouseName
		get.Price = float32(house.Price)
		Data.House = append(Data.House, &get)
	}
	var total int64
	if err := models.DB.Model(&models.House{}).Pluck("count(*)", &total).Error; err != nil {
		return &house_rpc.ListResponse{}, err
	}
	Data.Total = total
	return &Data, nil
}
